<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\Release as ReleaseModel;

class Release extends Controller
{
    /**
     * 获取发布列表
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param int $status 状态
     * @return json
     */
    public function list()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status/d', 0);

        $where = [];
        if ($status) {
            $where['status'] = $status;
        }

        $list = ReleaseModel::with(['user', 'category'])
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $count = ReleaseModel::where($where)->count();

        return json([
            'code' => 1,
            'data' => [
                'list' => $list,
                'total' => $count,
                'last_page' => ceil($count / $limit)
            ]
        ]);
    }

    /**
     * 审核发布
     * @param int $id 发布ID
     * @param int $status 状态 1通过 2拒绝
     * @param string $reason 拒绝原因
     * @return json
     */
    public function audit()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Release');
        if (!$validate->scene('audit')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $release = ReleaseModel::find($data['id']);
        if (!$release) {
            return json(['code' => 0, 'msg' => '数据不存在']);
        }

        $release->status = $data['status'];
        if ($data['status'] == 2) {
            $release->reason = $data['reason'];
        }

        if ($release->save()) {
            return json(['code' => 1, 'msg' => '操作成功']);
        }
        return json(['code' => 0, 'msg' => '操作失败']);
    }

    /**
     * 删除发布
     * @param int $id 发布ID
     * @return json
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        if (ReleaseModel::destroy($id)) {
            return json(['code' => 1, 'msg' => '删除成功']);
        }
        return json(['code' => 0, 'msg' => '删除失败']);
    }
} 